/**
 * hold gateways.
 */
var gateways = {};

function clearTimer(wait) {
	"use strict";
	var timerId = wait.timerId;
	clearTimeout(timerId);
}

function clearwait(gId, seq) {
	"use strict";
	var gateway = gateways[gId];
	var waits = gateway.waits;
	var wait = waits[seq];
	delete waits[seq];

	if (wait.callback.timeout) {
		wait.callback.timeout();
	}
}

gateways.handleSeqReply = function(cmd, body, c) {
	"use strict";
	var seq = cmd.seq;
	var devId = c.devId;

	var gateway = gateways[devId];
	if (!gateway) {
		return;
	}

	var waits = gateway.waits;
	var wait = waits[devId];
	if (wait) {
		delete waits[devId];
		clearTimer(wait);

		wait.callback.completed(cmd, body, c);
	}
};

gateways.addNew = function(g) {
	"use strict";
	gateways[g.devId] = g;
	g.seq = 0;
	g.waits = {};
};

gateways.del = function(gId) {
	"use strict";
	var g = gateways[gId];
	if (!g) {
		return;
	}

	delete gateways[gId];

	var waits = g.waits;
	for ( var x in waits) {
		if (waits.hasOwnProperty(x)) {
			var w = waits[x];
			clearTimeout(w.timerId);
			if (w.callback.error) {
				w.callback.error();
			}
		}
	}
};

gateways.sendAndWaitReply = function(gId, cmd, body, type, callback) {
	"use strict";
	var gateway = gateways[gId];
	if (!gateway) {
		console.error("sendAndWaitReply error, gateway " + gId + " not exist");
		return;
	}

	if (gateway.seq > 254) {
		gateway.seq = 0;
	}

	gateway.seq = gateway.seq + 1;
	cmd.seq = gateway.seq;
	var seq = cmd.seq;

	var wait = {};
	wait.seq = seq;
	wait.callback = callback;
	wait.timerId = setTimeout(function() {
		clearwait(gId, seq);
	}, 60 * 1000);

	gateway.waits[seq] = wait;

	gateway.c.sendCommand(cmd, body, type);
};

module.exports = gateways;
